//
//  NetworkPermissionManager.swift
//  deWaterMarkingProject
//
//  Created by admin on 2025/9/22.
//

import Foundation
import CoreTelephony
import Network

enum CellularPermissionState {
    case unknown
    case restricted
    case notRestricted
}

enum NetworkStatus {
    case unavailable
    case wifi
    case cellular
}

class NetworkPermissionManager {
    
    static let shared = NetworkPermissionManager()
    
    private let cellularData = CTCellularData()
    private let monitor = NWPathMonitor()
    private let queue = DispatchQueue(label: "NetworkPermissionMonitor")
    
    // 当前蜂窝权限状态
    private(set) var cellularPermissionState: CellularPermissionState = .unknown
    // 当前网络状态
    private(set) var networkStatus: NetworkStatus = .unavailable
    
    // 状态变化回调
    var onCellularPermissionChanged: ((CellularPermissionState) -> Void)?
    var onNetworkStatusChanged: ((NetworkStatus) -> Void)?
    
    private init() {
        setupCellularMonitor()
        setupNetworkMonitor()
    }
    
    private func setupCellularMonitor() {
        cellularData.cellularDataRestrictionDidUpdateNotifier = { [weak self] state in
            guard let self = self else { return }
            switch state {
            case .restrictedStateUnknown:
                self.cellularPermissionState = .unknown
            case .restricted:
                self.cellularPermissionState = .restricted
            case .notRestricted:
                self.cellularPermissionState = .notRestricted
            @unknown default:
                self.cellularPermissionState = .unknown
            }
            DispatchQueue.main.async {
                self.onCellularPermissionChanged?(self.cellularPermissionState)
            }
        }
    }
    
    private func setupNetworkMonitor() {
        monitor.pathUpdateHandler = { [weak self] path in
            guard let self = self else { return }
            if path.status == .satisfied {
                if path.usesInterfaceType(.wifi) {
                    self.networkStatus = .wifi
                } else if path.usesInterfaceType(.cellular) {
                    self.networkStatus = .cellular
                } else {
                    self.networkStatus = .unavailable
                }
            } else {
                self.networkStatus = .unavailable
            }
            DispatchQueue.main.async {
                self.onNetworkStatusChanged?(self.networkStatus)
            }
        }
        monitor.start(queue: queue)
    }
}
